﻿using AutoMapper;
using B.S.Orders.Domain;
using B.S.Orders.ErrorCord;
using B.S.Orders.Read.Api.Application.Commands.ProjectModelCommand;
using B.S.Orders.Read.Api.DTO;
using MediatR;
using SqlSugar;

namespace B.S.Orders.Read.Api.Application.CommandsHander.ProjectModelCommandHander
{
    public class QueryProjectModelCommandHander : IRequestHandler<QueryProjectModelCommand, APIPaging<List<ProjectDtos>>>
    {
        private readonly ISqlSugarClient db;
        private readonly IConfiguration config;
        private readonly IMapper mapper;

        public QueryProjectModelCommandHander(ISqlSugarClient db, IConfiguration config, IMapper mapper)
        {
            this.db = db;
            this.config = config;
            this.mapper = mapper;
        }

        public Task<APIPaging<List<ProjectDtos>>> Handle(QueryProjectModelCommand request, CancellationToken cancellationToken)
        {
            APIPaging<List<ProjectDtos>> result = new APIPaging<List<ProjectDtos>>();

            var item = db.Queryable<ProjectModel>()
                .InnerJoin<ProjectType>((a, b) => a.ProjectTypeId == b.ProjectTypeId)
                .Where((a, b) => a.Del == false)
                .Select((a, b) => new ProjectDtos
                {
                    ProjectId = a.ProjectId,
                    ProjectName = a.ProjectName,
                    ProjectNum = a.ProjectNum,
                    ProjectTime = a.ProjectTime,
                    ProjectPeople = a.ProjectPeople,
                    ProjectTypeId = b.ProjectTypeId,
                    Del = a.Del,
                    ProjectTypeName = b.ProjectTypeName,
                });

            result.TotalCount = item.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            item = item.OrderByDescending(a => a.ProjectId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            result.Code = APIEnum.success;
            result.Msg = "查询成功";
            result.Data = mapper.Map<List<ProjectDtos>>(item.ToList());

            return Task.FromResult(result);
        }
    }
}
